var superagent = require('superagent');
var cheerio = require('cheerio');

function getWeiXinHtml(res, webUrl = "https://mp.weixin.qq.com/s/Dc9h48oNsh82I760U1OdYg") {
  superagent.get(webUrl).end(function (err, sres) {
    let result = {}, contentItems = [];
    if (err) result.error = err
    let $ = cheerio.load(sres.text);
    let profile = $('span#profileBt').text()
    let publishTime=$('em#publish_time').text()
    let ipData=$('span#js_ip_wording').text()
    $('div.rich_media_content').children().each(function (i, e) {
      //测试代码
      let content = {}, mText = $(this).text()
      if (mText) {
        let code = $(this).find('code')
        if (code && code.length) content.code = mText
        else content.text = mText
      } else {
        let image = $(this).find('img')
        image.length && image.each(function (imgIdx, imgEle) {
          let imageSrc = $(this).attr('data-src')
          imageSrc = imageSrc && imageSrc.replace('https:', 'https://images.weserv.nl/?url=https:')
          content.image = imageSrc && `${imageSrc}&wxfrom=5&wx_lazy=1&wx_co=1`
        })
      }
      if (content.text || content.image || content.code) contentItems.push(content)
    });
    result.profile = profile
    result.publishTime = publishTime
    result.ipData = ipData
    result.content = contentItems
    res.json(result)  //返回json数据
    return result
  })
}

function getMovieDetail(res) {
  let subject = '1293475'
  let webUrl = `https://movie.douban.com/subject/${subject}`
  superagent.get(webUrl).end(function (err, sres) {
    let result = {data: {}}
    if (err) result.error = err
    let $ = cheerio.load(sres.text);
    let mainpic = $('div#mainpic > a.nbgnbg > img').attr('src')//图片
    let info = convertInfo($('div#info').text())
    let rating_num = $('div#interest_sectl > strong.ll.rating_num').text()
    let rating_people = $('div#interest_sectl > a.rating_people').text()
    let intra = $('div#link-report-intra').text()
    let celebrities = []
    let celebritiesDiv = $('div#celebrities > ul.celebrities-list.from-subject.__oneline')
    celebritiesDiv.children().each(function (i, e) {
      // console.log("=======", $(e).text())
      let avatar = $("a > div.avatar", $(e)).attr('style')
      avatar = avatar.substring(avatar.indexOf('(') + 1, avatar.indexOf(')'))
      let name = $("div.info > span.name > a.name", $(e)).text()
      let role = $("div.info > span.role", $(e)).text()
      celebrities.push({name, avatar, role})
    })
    let relatedPics = []
    let relatedPicDiv = $("div#related-pic > ul.related-pic-bd")
    relatedPicDiv.children().each(function (i, e) {
      let image = $('li > a > img', $(e)).attr('src')
      relatedPics.push(image)
    })
    // console.log("celebrities", celebrities)
    result.data = {mainpic, ...info, rating_num, rating_people, intra, celebrities, relatedPics}
    res.json(result)
  })
}

function convertInfo(strInfo) {
  let obj = {}
  let keyList = strInfo.match(/[\u4e00-\u9fa5/a-zA-Z]+[:]/g)//得到:及前面的key值
  let list = strInfo.split('\n').filter(item => item.indexOf(":") != -1)
  list.map(item => {
    let key = keyList.find(key => item.indexOf(key) != -1)
    let value = item.replace(new RegExp(`[${key} ]`, "g"), '')
    let mItem = {[key]: value}
    obj[key] = value
    return mItem
  })
  return obj
}

module.exports = {
  getWeiXinHtml,
  getMovieDetail
}

